package com.yuns.exam.service.impl;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.yuns.company.entity.CompanyInfoBase;
import com.yuns.company.entity.CompanyUserRel;
import com.yuns.company.mapper.CompanyInfoBaseMapper;
import com.yuns.company.mapper.CompanyUserRelMapper;
import com.yuns.exam.dto.ExamQuestionDto;
import com.yuns.exam.dto.ExamQuestionStatisDto;
import com.yuns.exam.dto.QuestionRandomDto;
import com.yuns.exam.entity.*;
import com.yuns.exam.mapper.*;
import com.yuns.exam.req.ExamRecordParm;
import com.yuns.exam.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yuns.exam.vo.ExamQuestionVO;
import com.yuns.exam.vo.ExamRecordVO;
import com.yuns.exam.vo.QuestionVO;


import com.yuns.exception.MyException;
import com.yuns.mas.common.StringUtils;
import com.yuns.util.ResultJson;
import io.netty.util.internal.StringUtil;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.yuns.web.param.FrontPage;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 考试记录表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2020-10-25
 */
@Service
public class ExamRecordServiceImpl extends ServiceImpl<ExamRecordMapper, ExamRecord> implements IExamRecordService {

     @Autowired
     private ExamRecordMapper examRecordMapper;

     @Autowired
     private ExamQuestionMapper examQuestionMapper;

     @Autowired
     private IExamRecordService examRecordService;

     @Autowired
     private ExamAnswerRecordMapper examAnswerRecordMapper;

     @Autowired
     private IExamAnswerRecordService examAnswerRecordService;

    @Autowired
     private IExamQuestionService examQuestionService;

     @Autowired
     private IExamQuestionOptionService examQuestionOptionService;

     @Autowired
     private IQuestionOptionService questionOptionService;

     @Autowired
     private  IExamService examService;

     @Autowired
     private IQuestionService questionService;

     @Autowired
     private QuestionMapper questionMapper;

     @Autowired
     private ExamMapper examMapper;

     @Autowired
     private CompanyUserRelMapper companyUserRelMapper;

     @Autowired
     private CompanyInfoBaseMapper companyInfoBaseMapper;

        @Override
        public Object selectExamRecordList(ExamRecordParm frontPage) {




            if(!frontPage.is_search()){
                List<ExamRecordVO> list =  baseMapper.selectExamRecordData(frontPage);
                list.forEach(item->{
                    String examid = item.getExaminationInfoID();
                    HashMap m = new HashMap();
                    m.put("selectedType","id");
                    m.put("type",examid);
                    List<HashMap<String,Object>> exams =  examMapper.selectList(m);
                    item.setPassGrade(String.valueOf(exams.get(0).get("pass_grade")));
                });
                return list;
            }
            Page<ExamRecordVO> page = new Page<>(frontPage.getPageNumber(),frontPage.getPageSize());
            List<ExamRecordVO> list = baseMapper.selectExamRecordData(page,frontPage);
            list.forEach(item->{
                String examid = item.getExaminationInfoID();
                HashMap m = new HashMap();
                m.put("selectedType","id");
                m.put("type",examid);
                List<HashMap<String,Object>> exams =  examMapper.selectList(m);
                item.setPassGrade(String.valueOf(exams.get(0).get("pass_grade")));
            });
            return   page.setRecords(list);
     }

    /**
     * 开始考试
     * @param examRecordVO
     * @return
     */
    @Override
    public Object beginExam(ExamRecordVO  examRecordVO) {
        if(examRecordVO.getMemberId() == null ||
                StringUtil.isNullOrEmpty(String.valueOf(examRecordVO.getMemberId()))){
            throw new MyException("用户id必须传");
        }

        ExamQuestionStatisDto examQuestionStatisDto = ExamQuestionStatisDto.builder().build();
            // 插入考试记录
        ExamRecord  examRecord = ExamRecord.builder().build();
        examRecord.setExaminationInfoID(Long.valueOf(examRecordVO.getExaminationInfoID()));
        examRecord.setMemberID(examRecordVO.getMemberId());
        if(examRecordVO.getEid()!=null) {
            examRecord.setEid(Integer.valueOf(examRecordVO.getEid()));// 所属企业
        }

        HashMap m = new HashMap();
        m.put("ExaminationInfoID",examRecordVO.getExaminationInfoID());
        m.put("MemberID",examRecordVO.getMemberId());
        m.put("EID",examRecordVO.getEid());

        EntityWrapper<ExamRecord> examRecordEntityWrapper = new EntityWrapper<>();
        examRecordEntityWrapper.setEntity(examRecord);
        List<ExamRecord> examRecords =   examRecordMapper.selectListSelf(m);

        ExamRecordVO examRecordVO1 = ExamRecordVO.builder().build();
        if(examRecords!=null && examRecords.size()>0){
            BeanUtils.copyProperties(examRecords.get(0),examRecordVO1);
            examRecordVO1.setExaminationInfoID(String.valueOf(examRecords.get(0).getExaminationInfoID()));
            examQuestionStatisDto.setExamRecord(examRecordVO1);
        }else {
            examRecord.setIsCheck(3); // 3 是否进入考试判断
            examRecord.setBTime(new Date());
            examRecord.setAScroe(examRecordVO.getAScroe());// 总分

            examRecordMapper.insertExamRecord(examRecord);
            BeanUtils.copyProperties(examRecord,examRecordVO1);
            examRecordVO1.setExaminationInfoID(String.valueOf(examRecord.getExaminationInfoID()));
            examQuestionStatisDto.setExamRecord(examRecordVO1);
        }


        HashMap map = new HashMap();
        map.put("exam_id",Long.valueOf(examRecordVO.getExaminationInfoID()));
        map.put("question_source",0);
        List<ExamQuestion> examQuestions =  examQuestionMapper.selectExamQuestionByMap(map);
        Exam t = Exam.builder().build();
        t.setId(Long.valueOf(examRecordVO.getExaminationInfoID()));
        HashMap c = new HashMap();
        c.put("selectedType","id");
        c.put("type",examRecordVO.getExaminationInfoID());
        List<HashMap<String,Object>> exams = examMapper.selectList(c);
        examQuestionStatisDto.setExam(exams.get(0));

        List<ExamQuestionDto> rdata = Lists.newArrayList();
        List<ExamQuestionVO> examQuestionVOS = Lists.newArrayList();
        List<ExamQuestion>  examQuestions1 =
                examQuestions.stream().sorted(Comparator.comparing(ExamQuestion::getId)).collect(Collectors.toList());
        int i = 1;
        for(ExamQuestion eq:examQuestions1){
            ExamQuestionVO examQuestionVO = ExamQuestionVO.builder().build();
            BeanUtils.copyProperties(eq,examQuestionVO);
            examQuestionVO.setIndex(i);
            examQuestionVO.setId(String.valueOf(eq.getId()));
            examQuestionVOS.add(examQuestionVO);
            i++;
        }
        Map<Integer,  Long> map1 =
                examQuestions.stream().collect(Collectors.groupingBy(ExamQuestion::getQuestionType,Collectors.counting()));
       List<Integer> ls = Lists.newArrayList();

        List<Integer> typeList =  new ArrayList<>(Arrays.asList(0,1, 2, 3));
        for (Integer key : map1.keySet()) {
            ls.add(key);
        }
        for(Integer t1:typeList){
            if(!ls.contains(t1)){
                map1.put(t1,0L);
            }
        }

        examQuestionStatisDto.setTotalMap(map1);
        EntityWrapper<QuestionOption> examQuestionOptionEntityWrapper = new EntityWrapper<>();
        QuestionOption examQuestionOption = new QuestionOption();
        examQuestionVOS.forEach(item->{
            ExamQuestionDto examQuestionDto = ExamQuestionDto.builder().build();
            examQuestionOption.setQuestionId(item.getQuestionId());
            examQuestionOptionEntityWrapper.setEntity(examQuestionOption);
            List<QuestionOption> examQuestionOptionList =
                    questionOptionService.selectList(examQuestionOptionEntityWrapper);

            examQuestionDto.setExamQuestionVO(item);
            examQuestionDto.setQuestionOptions(examQuestionOptionList);
            rdata.add(examQuestionDto);
        });


        //插入考试题目记录 已有考试不用再插入
        List<ExamAnswerRecord> examAnswerRecords = Lists.newArrayList();
        if(examRecords==null || examRecords.size()==0) {
            for(ExamQuestion item:examQuestions){
                ExamAnswerRecord examAnswerRecord = ExamAnswerRecord.builder().build();
                examAnswerRecord.setExamTitleId(examRecordVO.getExaminationInfoID().toString());
                examAnswerRecord.setQuestionId(String.valueOf(item.getQuestionId()));//来源gt_exam_question(题库)的id
                examAnswerRecord.setQuestionType(item.getQuestionType());
                examAnswerRecord.setScore(new BigDecimal(0));
                examAnswerRecord.setMemberID(examRecordVO.getMemberId());
                if (examRecords != null && examRecords.size() > 0) {
                    examAnswerRecord.setExamRecordId(String.valueOf(examRecords.get(0).getId()));
                } else {
                    examAnswerRecord.setExamRecordId(String.valueOf(examRecord.getId()));
                    examAnswerRecord.setIsOK("0");
                }

                examAnswerRecords.add(examAnswerRecord);
            }
            Boolean r = examAnswerRecordService.insertBatch(examAnswerRecords);
        }else{
            ExamAnswerRecord examAnswerRecord = ExamAnswerRecord.builder().build();
            examAnswerRecord.setExamTitleId(String.valueOf(examRecords.get(0).getExaminationInfoID()));
            examAnswerRecord.setExamRecordId(examRecords.get(0).getId());
            examAnswerRecord.setMemberID(examRecords.get(0).getMemberID());
            EntityWrapper<ExamAnswerRecord> examAnswerRecordEntityWrapper
                    = new EntityWrapper<>();
            examAnswerRecordEntityWrapper.setEntity(examAnswerRecord);
            examAnswerRecords =
                   examAnswerRecordService.selectList(examAnswerRecordEntityWrapper);

        }
        Map<String,List<ExamAnswerRecord>> exRecords =
                examAnswerRecords.stream().collect(Collectors.groupingBy(ExamAnswerRecord::getQuestionId));
        rdata.forEach(item->{
            List<ExamAnswerRecord> examAnswerRecords1 =  exRecords.get(String.valueOf(item.getExamQuestionVO().getQuestionId()));
            if(examAnswerRecords1!=null && examAnswerRecords1.size()>0 ){
                item.setExamAnswerRecord(examAnswerRecords1.get(0));
            }
        });
        examQuestionStatisDto.setQuestionDto(rdata);
        return examQuestionStatisDto;
    }


    /**
     * 试卷分析
     * @param examRecordVO
     * @return
     */
    public Object paperAnalysis(ExamRecordVO  examRecordVO){
        ExamQuestionStatisDto examQuestionStatisDto = ExamQuestionStatisDto.builder().build();
         examQuestionStatisDto = (ExamQuestionStatisDto) beginExam(examRecordVO);

         ExamAnswerRecord examAnswerRecord = ExamAnswerRecord.builder().build();
         examAnswerRecord.setExamTitleId(examRecordVO.getExaminationInfoID().toString());
         examAnswerRecord.setExamRecordId(examRecordVO.getId());


         return null;
    }

    public void executeExamMsgTip(){
//        ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
//
//
//        // 参数：1、任务体 2、首次执行的延时时间
//        //      3、任务执行间隔 4、间隔时间单位
//        service.schedule(()->
//                System.out.println("task ScheduledExecutorService "+new Date()),3,
//                TimeUnit.SECONDS);
    }

    /**
     * 答题后记录到题目的记录信息中
     * @param examAnswerRecord
     * @return
     */
    @Override
    public Object updateExamAnswerRecord(ExamAnswerRecord examAnswerRecord) {
        examAnswerRecord.setUpdateTime(new Date());
        ExamAnswerRecord updateExamAnswerRecord = ExamAnswerRecord.builder().
                Answer(examAnswerRecord.getAnswer()).
                id(examAnswerRecord.getId()).
                isOk(examAnswerRecord.getIsOK()).
                Score(examAnswerRecord.getScore()).
                answerReply(examAnswerRecord.getAnswerReply()).
                updateTime(new Date()).build();
        Boolean r = examAnswerRecordService.updateById(updateExamAnswerRecord);
        return updateExamAnswerRecord;
    }

    @Override
    public Object submitExam(ExamRecordVO examRecordVO) {
        Date now=new Date();
        String pattern="yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat dtf = new SimpleDateFormat(pattern);
        examRecordVO.setETime(dtf.format(now));
        ExamRecord examRecord = ExamRecord.builder().build();
        BeanUtils.copyProperties(examRecordVO, examRecord);
        if(examRecordVO.getId() == null){
            throw  new MyException("考试记录一定要输入");
        }
        examRecord.setId(examRecordVO.getId());
        examRecord.setMemberID(examRecordVO.getMemberId());
        try {
            examRecord.setBTime(dtf.parse(examRecordVO.getBTime()));

            examRecord.setETime(now);
            // 强制提交试卷没有做完的题目都为0分 并且标记题目已经提交
            ExamAnswerRecord t = ExamAnswerRecord.builder().build();
            t.setExamRecordId(examRecordVO.getId()); // 考试记录
            t.setUpdateTime(now);
            t.setExamTitleId((examRecordVO.getExaminationInfoID()).toString());// 使用的试卷
            t.setMemberID(examRecordVO.getMemberId());

            Boolean ret = examAnswerRecordService.updateSign(t);
            Map m = new HashMap();
            m.put("exam_title_id",examRecordVO.getExaminationInfoID());
            m.put("member_id",examRecordVO.getMemberId());
            m.put("exam_record_id",examRecordVO.getId());
            List<ExamAnswerRecord> examAnswerRecords =  examAnswerRecordService.selectByMap(m);
            // 计算最后考试成绩
            Double t1 = examAnswerRecords.stream().mapToDouble(e->e.getScore().doubleValue()).reduce(0,Double::sum);
            examRecord.setScore(new BigDecimal(t1));
            if(examRecordVO.getIsCheck()!=null) {
                examRecord.setIsCheck(examRecordVO.getIsCheck());
            }
            if(examRecordVO.getScore()!=null){
                examRecord.setScore(examRecordVO.getScore());//试题的成绩分
            }
            // 交卷时，有简答题，传2 ，没有就传1
            examRecordService.updateExamRecord(examRecord);
        }catch (Exception e){
            throw  new MyException("请检查参数");
        }
        return  examRecord;
    }

    @Override
    public Object selectErrorQuestionListByQuestionType(FrontPage<QuestionVO> frontPage) {
        List<ExamQuestionDto>  examQuestionDtos = Lists.newArrayList();
        if (!frontPage.is_search()) {
            List<ExamQuestion> examQuestions = examAnswerRecordMapper.selectErrorQuestionListByQuestionType(frontPage);

            examQuestions.forEach(item->{
                ExamQuestionDto examQuestionDto = ExamQuestionDto.builder().build();
                examQuestionDto.setExamQuestion(item);
                HashMap map = new HashMap();
                map.put("question_id",item.getQuestionId());
                List<QuestionOption> questionOptions =  questionOptionService.selectByMap(map);
                examQuestionDto.setQuestionOptions(questionOptions);
                examQuestionDtos.add(examQuestionDto);
            });
            return examQuestionDtos;

        }
        Page<QuestionVO> page = new Page<>(frontPage.getPageNumber(), frontPage.getPageSize());
        List<ExamQuestion> list = examAnswerRecordMapper.selectErrorQuestionListByQuestionType(page, frontPage);

        list.forEach(item->{
            ExamQuestionDto examQuestionDto = ExamQuestionDto.builder().build();
            examQuestionDto.setExamQuestion(item);
            HashMap map = new HashMap();
            map.put("question_id",item.getQuestionId());
            List<QuestionOption> questionOptions =  questionOptionService.selectByMap(map);
            examQuestionDto.setQuestionOptions(questionOptions);
            examQuestionDtos.add(examQuestionDto);
        });
        Page<ExamQuestionDto> pages = new Page<>(frontPage.getPageNumber(), frontPage.getPageSize());
        pages.setTotal(page.getTotal());
        return pages.setRecords(examQuestionDtos);
    }

    @Override
    public void updateExamRecord(ExamRecord examRecord) {
         baseMapper.updateExamRecord(examRecord);
    }

    /**
     * 模拟考试
     */
    @Override
    @Transactional
    public  ExamQuestionStatisDto testExam(){

        ExamQuestionStatisDto examQuestionStatisDto = ExamQuestionStatisDto.builder().build();


        // 生成试卷100分 随机抽
         Exam t = Exam.builder().examName("模拟考试").grade("100").questionSource(2).build();
         examService.insert(t);

//        QueryWrapper<Question> wrapper = new QueryWrapper<>();

        EntityWrapper<Question> entityWrapper = new EntityWrapper<>();
        entityWrapper.in("question_type_sel","1,2,3");

        List<ExamQuestionDto> examQuestionDtos = Lists.newArrayList();

        Map<Integer,  Long> map = new HashMap<>();
        map.put(0,3L);
        map.put(1,3L);
        map.put(2,4L);
        examQuestionStatisDto.setTotalMap(map);
        LinkedList<Question> questions = new LinkedList();
        questions.addAll(getQuestion(3,0));
        questions.addAll(getQuestion(3,1));
        questions.addAll(getQuestion(4,2));
        int i = 1;
        for(Question item: questions){
            ExamQuestionDto examQuestionDto = ExamQuestionDto.builder().build();
            ExamQuestionVO examQuestionVO = ExamQuestionVO.builder().build();
            examQuestionVO.setAnalysis(item.getAnalysis());
            examQuestionVO.setQuestionAnswer(item.getQuestionAnswer());
            examQuestionVO.setQuestionTitle(item.getQuestionTitle());
            examQuestionVO.setQuestionType(item.getQuestionTypeSel());
            examQuestionVO.setQuestionId(String.valueOf(item.getId()));
            examQuestionVO.setExamId(String.valueOf(t.getId()));
            examQuestionVO.setIndex(i);
            examQuestionDto.setExamQuestionVO(examQuestionVO);

//            EntityWrapper<QuestionOption> examQuestionOptionEntityWrapper =
//                    new EntityWrapper<>();
//            QuestionOption examQuestionOption = new QuestionOption();
//            examQuestionOption.setQuestionId(String.valueOf(item.getId()));
//            examQuestionOptionEntityWrapper.setEntity(examQuestionOption);
//            List<QuestionOption> examQuestionOptionList =
//                    questionOptionService.selectList(examQuestionOptionEntityWrapper);
//
//            examQuestionDto.setQuestionOptions(examQuestionOptionList);
            examQuestionDtos.add(examQuestionDto);
            i++;
        };


        //插入考试题目记录
//        List<ExamAnswerRecord> examAnswerRecords = Lists.newArrayList();
//        questions.forEach(item->{
//            ExamAnswerRecord examAnswerRecord = ExamAnswerRecord.builder().build();
//            examAnswerRecord.setExamTitleId(String.valueOf(t.getId())); //来源gt_exam(题库)的id
//            examAnswerRecord.setQuestionId(String.valueOf(item.getId()));//来源gt_exam_question(题库)的id
//            examAnswerRecord.setQuestionType(item.getQuestionTypeSel());
//            examAnswerRecord.setScore(new BigDecimal(0));
//            examAnswerRecord.setExamRecordId("111");
//            examAnswerRecord.setIsOK("0");
//            examAnswerRecords.add(examAnswerRecord);
//        });
//        Boolean r = examAnswerRecordService.insertBatch(examAnswerRecords);

//        Map<String,List<ExamAnswerRecord>> examRecordMap =
//        examAnswerRecords.stream().collect(Collectors.groupingBy(ExamAnswerRecord::getQuestionId));
//        examQuestionDtos.forEach(item->{
//            if(examRecordMap.get(item.getExamQuestionVO().getQuestionId())!=null){
//                item.setExamAnswerRecord(examRecordMap.get(item.getExamQuestionVO().getQuestionId()).get(0));
//            }
//        });
//
        examQuestionStatisDto.setQuestionDto(examQuestionDtos);

        return examQuestionStatisDto;

    }

    /**
     *
     * @param companyCode
     * @param time
     * @param index
     * @return HBJ202011113456
     */
    @Override
    public String genCertificateEncoding(String companyCode, String time, String index) {
        StringBuffer cer = new StringBuffer();
        cer.append(companyCode);
        cer.append(time.replaceAll("-","").replaceAll(" ", "").replaceAll(":",""));
        cer.append(index);

        return cer.toString();
    }

    private List<Question> getQuestion(Integer questionNum,Integer questionType) {
        Question t0 = Question.builder().
                questionNum(questionNum).questionTypeSel(questionType).build();
        List<Question> questions1 = questionMapper.selectQuestionListByRandom(t0);
        return questions1;
    }

    @Override
    public Object sendCertificate(ExamRecordVO examRecordVO){

        Integer companyUserId = examRecordVO.getMemberId();
        HashMap c = new HashMap();
        c.put("company_user_id", companyUserId);
       List<CompanyUserRel> companyUserRels =  companyUserRelMapper.selectByMap(c);
        CompanyUserRel companyUserRel = null;
        if(companyUserRels!=null && companyUserRels.size()>0) {
             companyUserRel = companyUserRels.get(0);

        CompanyInfoBase companyInfoBase =  new CompanyInfoBase();
        companyInfoBase.setId(companyUserRel.getCompanyId());
        //  时间，单位名称，证书编号，二维码

        String dateStr = DateUtil.format(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss");
        String cerNo =  genCertificateEncoding("HBJ" + String.valueOf(companyUserRel.getCompanyId()),dateStr,genCertificateIndex());
        companyInfoBase.setCertNo(cerNo);
            Date now=new Date();
            String pattern="yyyy-MM-dd HH:mm:ss";
            SimpleDateFormat dtf = new SimpleDateFormat(pattern);
            companyInfoBase.setCreateTime(dtf.format(now));// 证书获取时间
        companyInfoBaseMapper.updateById(companyInfoBase);
            return companyInfoBase;
        }
        return  null;

    }

    /**
     * 下发证书，需要得到  证书编号，获取时间，单位名称
     * 查询证书，需要得到二维码，获取时间，单位名称
     * @return
     */
    @Override
    public Object queryCertificate(ExamRecordVO examRecordVO){
        Integer companyUserId = examRecordVO.getMemberId();
        HashMap c = new HashMap();
        c.put("company_user_id", companyUserId);
        List<CompanyUserRel> companyUserRels =  companyUserRelMapper.selectByMap(c);
        CompanyUserRel companyUserRel = null;
        CompanyInfoBase companyInfoBase = null;
        if(companyUserRels!=null && companyUserRels.size()>0) {
            companyUserRel = companyUserRels.get(0);
            companyInfoBase = companyInfoBaseMapper.selectById(companyUserRel.getCompanyId());
            if(companyInfoBase == null){
                return ResultJson.ok("该企业无证书");
            }
        }else{
            return ResultJson.ok("该企业无证书");
        }

        return companyInfoBase;
    }


    public String genCertificateIndex(){

        String[] chars = new String[] { "a", "b", "c", "d", "e", "f",
                "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
                "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
                "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
                "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z" };
        StringBuffer shortBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 4; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars[x % 0x3E]);
        }
        String suffix = shortBuffer.toString();
        return suffix;
    }
}
